<template>
	<view>
		<view class="top-nav">
			<uni-nav-bar title="视频监控" backgroundColor="transparent" color="#f0f0f0" statusBar="true" @clickLeft="back"
				left-icon="arrowleft"></uni-nav-bar>
		</view>
		<view class="contain-view">
			<view class="header">
				<view class="title">
					<image class="icon" src="@/static/agricultural/wulianwang.png" mode="heightFix"></image>
					{{ cameraInfo.cameraName }}
				</view>
				<view class="toVideo" @click="toEnvData">
					<uni-icons type="tune" :color="'#fff'" size="20" class="icon" />
					查看物联数据
				</view>
			</view>
			<!-- <view class="select-camera">
				<image class="icon-sty" src="@/static/instrumented-monitoring/video-surveillance/cameraType1.png"
					mode="aspectFit"></image>
				<view class="select-picker">
					<picker @change="cameraChange" :value="cameraListIndex" :range="cameraList" range-key="cameraName">
						<view>{{ cameraList[cameraListIndex].cameraName }}</view>
					</picker>
				</view>
			</view> -->
			<view class="video-view">
				<!-- 播放器 -->
				<video id="myVideo" :src="cameraurl" :autoplay="isautoplay" :controls="isDefinitionBtnShow"
					:show-fullscreen-btn="true" :show-play-btn="false" object-fit="cover" class="zhvideo-sty"
					@fullscreenchange="playerFullScreen" play-strategy="3">
					<!-- <cover-view class="video-definition-btn" @click="showDefinitionOption" v-if="isDefinitionBtnShow">退出全屏</cover-view> -->
				</video>
				<!-- 点击全屏 -->
				<view class="fullscreen" @click="quanpin()">
					<image class="icon-sty" mode="aspectFit"
						src="@/static/instrumented-monitoring/video-surveillance/fullscreen.png"></image>
				</view>
			</view>
			<scroll-view scroll-y="true" class="cotrol-view" v-if="userType === 'platform_user' && controlFlag" :style="{ height: layscrolljj + 'px' }">
				<view class="cotrol-view">
					<view class="control-view-line1">
						<button class="min-but qipao-but tobig" @click="myControlCamera(8)">
							<image class="icon-sty" src="@/static/instrumented-monitoring/video-surveillance/tobig.png"
								mode="heightFix"></image>
							放大
						</button>
						<view class="min-but qipao-but tosmall" @click="myControlCamera(9)">
							<image class="icon-sty"
								src="@/static/instrumented-monitoring/video-surveillance/tosmall.png" mode="heightFix">
							</image>
							缩小
						</view>
					</view>
					<view class="control-view-line2">
						<view class="totop" @click="myControlCamera(0)">
							<view class="sanjiao"></view>
						</view>
						<view class="toright" @click="myControlCamera(3)">
							<view class="sanjiao"></view>
						</view>
						<view class="tobottom" @click="myControlCamera(2)">
							<view class="sanjiao"></view>
						</view>
						<view class="toleft" @click="myControlCamera(1)">
							<view class="sanjiao"></view>
						</view>
						<view class="fanzhuan" @click="fanzhuanmet()"></view>
					</view>
					<view class="min-but qipao-but control-view-line3" @click="duankai()">
						<image class="icon-sty" src="@/static/instrumented-monitoring/video-surveillance/toshutdown.png"
							mode="heightFix"></image>
						断开
					</view>
				</view>
				<view class="bottom-ios-line"></view>
			</scroll-view>
			<view class="blank-view" v-if="userType === 'platform_user' && !controlFlag" :style="{ height: layscrolljj + 'px' }">
				<image class="blank-sty" src="@/static/blank.png" mode="heightFix"></image>
				<view class="blank-title">设备不可控，请选择可控设备</view>
				<view class="bottom-ios-line"></view>
			</view>
			<view>
				<!-- 普通弹窗 -->
				<uni-popup ref="popup" background-color="#fff" :mask-click="false" @change="change">
					<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
						<text class="text" v-if='!popupSTu'>摄像头启动倒计时{{ count || '0' }}秒</text>
						<text class="text"
							style="height: 12rpx; width: 100%; border: 1rpx solid rgb(72, 198, 155); display: flex;border-radius: 6rpx;"
							v-if='!popupSTu'>
							<view class="texts" style="height: 100%;background: rgb(72, 198, 155);" :style='{
								width: (100 - ( count / openTime  * 100)) + "%" }'>
							</view>
						</text>
						<text class="text" style="font-size: 24rpx;" v-else>特殊摄像头<br>启动倒计时</text>
					</view>
				</uni-popup>
			</view>
		</view>
	</view>
</template>

<script>
	import agriculturalApi from '@/api/socialized-servce/agricultural-information/index.js'
	export default {
		data() {
			return {
				userType: uni.getStorageSync('userType'),
				isgroup: false, //是否是设施组
				// 摄像头列表
				cameraList: [{
					cameraName: '暂无数据'
				}],
				cameraListIndex: 0,
				// 摄像头播放地址
				cameraurl: '',
				// 是否开始播放视频
				isautoplay: false,
				// 摄像头是否可控
				controlFlag: false,
				// 全屏按钮展示
				isDefinitionBtnShow: false,
				// 当前选择的地块信息
				facilitymessage: {},
				cameraId: '',
				openSourceMark: '',
				count: 0,
				openTime: 0,
				type: 'center',
				popupSTu: false
			};
		},
		onLoad(e) {
			this.navparams = { ...e }
			this.cameraInfo = {
				cameraId: e.cameraId,
				cameraName: this.$param(e.cameraName)
			}
			if (e.facilityGroupNo) {
				this.isgroup = true;
				this.facilitymessage = {
					facilityNo: e.facilityGroupNo,
					facilityName: this.$param(e.facilityName)
				};
			} else if (e.facilityNo) {
				this.facilitymessage = {
					facilityNo: e.facilityNo,
					facilityName: this.$param(e.facilityName)
				};
			}
		},
		onShow() {
			this.getCamerMessage();
		},
		beforeDestroy() {
			if (this.cameraId && this.openSourceMark) {
				this.closePower(this.cameraId, this.openSourceMark);
				clearInterval(this.timer);
			}
		},

		onHide() {
			if (this.cameraId && this.openSourceMark) {
				this.closePower(this.cameraId, this.openSourceMark);
				clearInterval(this.timer);
			}
		},
		computed: {
			layscrolljj: function() {
				let winHeight = 0;
				let botbarheight = uni.upx2px(590);
				uni.getSystemInfo({
					success: function(res) {
						winHeight = res.windowHeight;
						// let modelmes = res.model
					}
				});
				winHeight = parseInt(winHeight) - botbarheight - this.customBar;
				return winHeight;
			}
		},
		methods: {
			toEnvData() {
				let navurl = '/subPage1/socialized-service/agricultural-information/agricultural-detail/environmental-data'
				this.$togo(navurl, this.navparams)
			},
			// 获取所有摄像头信息
			getCamerMessage() {
				let data;
				if (this.isgroup) {
					data = {
						facilityGroupNo: this.facilitymessage.facilityNo
					};
				} else {
					data = {
						facilityNo: this.facilitymessage.facilityNo
					};
				}
				
				this.chanceCamera(this.cameraInfo, 0);
				this.cameraList = [this.cameraInfo];
				// agriculturalApi.queryByFacilityNo({
				// 	facilityNo: data.facilityNo
				// }).then(
				// // this.$zhreq.requst('v3/iot/cameraFacilityMapper/queryByFacilityNo?facilityNo=' + data.facilityNo).then(
				// 	res => {
				// 		let listone = res.data;
				// 		this.cameraList = res.data;
				// 		this.cameraList.forEach(item => {
				// 			this.$set(item, 'cameraName', item.camera?.cameraName);
				// 		});
				// 		if (listone[0] !== undefined) {
				// 			this.chanceCamera(listone[0], 0);
				// 		}
				// 	});
			},
			// 选择了摄像头
			cameraChange(e) {
				this.cameraListIndex = e.target.value;
				this.chanceCamera(this.cameraList[this.cameraListIndex], this.cameraListIndex);
			},
			// 点击摄像头,选择相应摄像头
			async chanceCamera(e, i) {
				// console.log(e);
				// 判断是否需要关闭摄像头
				// if (this.openSourceMark && this.cameraId && this.cameraId !== e.camera.cameraId) {
				// 	await this.closePower(this.cameraId, this.openSourceMark);
				// }
				// 判断流量是否超出
				// 判断是否需要调用预加载
				// if (e.camera.startUp === 'true') {
				// 	let openSourceMark = this.getProjectNum() + Math.floor(Math.random() * 10000000);
				// 	await this.openPower(e.camera.cameraId, openSourceMark);
				// } else {
					if (await this.setiotApp(e.cameraId)) {
						uni.showToast({
							title: '萤石云流量不足，功能受限',
							icon: 'none'
						});
						// return;
					} else {
						let cameramessage = await this.setcameramessage(e.cameraId);
						// console.log(cameramessage)
						if (cameramessage && cameramessage.cameraInfo && cameramessage.cameraInfo.status === 1) {
							this.getCameraApi(cameramessage);
						} else {
							uni.showToast({
								title: '设备未在线，请稍后重试',
								icon: 'none'
							});
						}
						this.controlFlag = cameramessage.controlFlag;
					}
				// }
			},

			change(e) {
				console.log('启动倒计时：' + this.count);
				// this.countDown(e)
			},
			countDown(e, x) {
				let _this = this;
				const TIME_COUNT = e;
				if (!this.timer) {
					this.count = TIME_COUNT;
					this.timer = setInterval(() => {
						if (this.count > 0 && this.count <= TIME_COUNT) {
							this.count--;
							if (this.count === x) {
								this.popupSTu = false
							}
						} else {
							_this.$refs.popup.close();
							clearInterval(this.timer);
							this.timer = null;
						}
					}, 1000);
				}
			},
			// // 进行摄像头预热
			async openPower(cameraId, openSourceMark) {
				let zhrequrl = `https://tdiot.cloud/iotApplication/solarEnergyCamera/openPower`;
				// return new Promise(resove => {
				uni.request({
					url: zhrequrl,
					data: {
						cameraId: cameraId,
						openSourceMark: openSourceMark.toString()
					},
					method: 'POST',
					success: res => {
						let newArr = res.data.data;
						this.openSourceMark = openSourceMark;
						this.cameraId = cameraId;
						// console.log(newArr);
						this.$refs.popup.open('center');
						this.popupSTu = true
						this.openTime = newArr.openTime * 60
						this.countDown((newArr.openTime * 60) + 2, newArr.openTime * 60);
						// this.countDown(newArr.openTime);
						setTimeout(async () => {
							if (await this.setiotApp(cameraId)) {
								uni.showToast({
									title: '萤石云流量不足，功能受限',
									icon: 'none'
								});
								// return;
							} else {
								let cameramessage = await this.setcameramessage(cameraId);
								// console.log(cameramessage)
								if (cameramessage && cameramessage.cameraInfo && cameramessage
									.cameraInfo.status === 1) {
									this.getCameraApi(cameramessage);
								} else {
									uni.showToast({
										title: '设备未在线，请稍后重试',
										icon: 'none'
									});
								}
								this.controlFlag = cameramessage.controlFlag;
							}
						}, ((newArr.openTime * 60) + 2) * 1000);
						// resove(newArr);
					}
				});
				// });
			},
			// 关闭摄像头
			async closePower(cameraId, openSourceMark) {
				let zhrequrl = `https://tdiot.cloud/iotApplication/solarEnergyCamera/closePower`;
				// return new Promise(resove => {
				uni.request({
					url: zhrequrl,
					data: {
						cameraId: cameraId,
						openSourceMark: openSourceMark.toString()
					},
					method: 'POST',

					success: res => {
						let newArr = res.data.data;
						// this.openSourceMark = openSourceMark
						this.openSourceMark = '';
						this.cameraId = '';
						console.log(newArr);
						// resove(newArr);
					}
				});
				// });
			},

			// 获取摄像头流量
			async setiotApp(cameraId) {
				let zhrequrl = `https://tdiot.cloud/iotApplication/cameraOperation/judgeFlow?cameraId=${cameraId}`;
				// return new Promise(resove => {
				uni.request({
					url: zhrequrl,
					method: 'GET',
					success: res => {
						let newArr = res.data.basis;
						// console.log(res.data.data)
						if (res.data.data !== undefined) {
							if (res.data.data.flowUse !== undefined) {
								uni.showToast({
									title: '剩余流量' + res.data.data.flowUse || '',
									icon: 'none'
								});
							}
						}
						// console.log(newArr)
						// resove(newArr);
					}
				});
				// });
			},
			// 时间
			getProjectNum() {
				let projectTime = new Date();
				const Year = projectTime.getFullYear(); // 获取当前年份⽀持IE和⽕狐浏览器.
				const Month = projectTime.getMonth() + 1; // 获取中国区⽉份
				const Day = projectTime.getDate(); // 获取⼏号
				var CurrentDate = String(Year);
				if (Month >= 10) {
					// 判断⽉份和⼏号是否⼤于10或者⼩于10
					CurrentDate += Month;
				} else {
					CurrentDate += '0' + Month;
				}
				if (Day >= 10) {
					CurrentDate += Day;
				} else {
					CurrentDate += '0' + Day;
				}
				return CurrentDate;
			},
			// 设置摄像头的详细信息
			async setcameramessage(cameraId) {
				// let zhrequrl = `v3/iot/platformCamera/queryCameraAllInfo?cameraId=${cameraId}`;
				return new Promise(resove => {
					agriculturalApi.queryCameraAllInfo(cameraId).then(res => {
					// this.$zhreq.requst(zhrequrl, {}, 'post').then(res => {
						let newArr = res.data.camera;
						// console.log(newArr)
						resove(newArr);
					});
				});
			},
			// 获取当前视频的播放的地址
			getCameraApi(e) {
				let params = {
					accessToken: e.accessToken,
					deviceSerial: e.deviceSerial,
					channelNo: e.channelNo,
					protocol: 2
				};
				uni.request({
					url: 'https://open.ys7.com/api/lapp/v2/live/address/get',
					method: 'POST',
					data: params || {},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
					},
					success: res => {
						this.cameraurl = res.data.data.url;
						this.isautoplay = true;
						// console.log("------")
						// console.log(this.cameraurl)
					}
				});
			},
			// ----摄像头控制相关---
			// 对摄像头进行控制
			// 操作命令：0-上，1-下，2-左，3-右，4-左上，5-左下，6-右上，7-右下，8-放大，9-缩小，10-近焦距，11-远焦距
			// "'speed': 云台速度：0-慢，1-适中，2-快，海康设备参数不可为0
			myControlCamera(id) {
				let reqparams = {
					cameraId: this.cameraList[this.cameraListIndex].cameraId,
					direction: id,
					speed: 1,
					actionType: 'start'
				};
				agriculturalApi.action(reqparams).then(res => {
					if (res.data.code != 200) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
						});
					}
					// console.log(res.data.msg)
					setTimeout(() => {
						this.stopcamera(id);
					}, 1000);
				})
				// let requrl = 'v3/iot/cameraOperation/start';
				// this.$zhreq.requst(requrl, reqparams, 'post').then(res => {
				// 	// console.log(res.data.msg)
				// 	setTimeout(() => {
				// 		this.stopcamera(id);
				// 	}, 1000);
				// });
			},
			// 镜像翻转0-上下, 1-左右, 2-中心
			fanzhuanmet() {
				let reqparams = {
					cameraId: this.cameraList[this.cameraListIndex].cameraId,
					command: 2,
					actionType: 'mirror'
					// "direction" :id,
					// "speed":1
				};
				agriculturalApi.action(reqparams).then(res => {
					// console.log(res.data.msg)
					setTimeout(() => {
						this.stopcamera(id);
					}, 1000);
				})
				// let requrl = 'v3/iot/cameraOperation/mirror';
				// this.$zhreq.requst(requrl, reqparams, 'post').then(res => {
				// 	// console.log(res.data.msg)
				// 	setTimeout(() => {
				// 		this.stopcamera(id);
				// 	}, 1000);
				// });
			},
			//停止转动
			stopcamera(id) {
				let reqparams = {
					cameraId: this.cameraList[this.cameraListIndex].cameraId,
					direction: id,
					speed: 1,
					actionType: 'stop'
				};
				agriculturalApi.action(reqparams).then(res => {
					// console.log(res.data.msg)
				})
				// let requrl = 'v3/iot/cameraOperation/stop';
				// this.$zhreq.requst(requrl, reqparams, 'post').then(res => {
				// 	// console.log(res.data.msg)
				// });
			},
			//断开连接
			duankai() {
				this.cameraurl = '';
			},
			// ----播放器全屏相关----
			// 退出全屏
			showDefinitionOption() {
				let myurl =
					`video-surveillance?facilityNo=${this.facilitymessage.facilityNo}&facilityName=${this.facilitymessage.facilityName}`;
				uni.redirectTo({
					url: myurl
				});
			},
			// 监测是否全屏
			playerFullScreen(e) {
				if (e.detail.fullScreen) {
					//全屏
					this.isDefinitionBtnShow = true;
				} else {
					//非全屏
					this.isDefinitionBtnShow = false;
				}
			},
			//全屏方法
			quanpin() {
				// 获取 video 上下文 videoContext 对象
				// videoContext = uni.createVideoContext('myVideo');
				// 进入全屏状态
				uni.createVideoContext('myVideo').requestFullScreen();
				this.isDefinitionBtnShow = true;
			},

			//--------顶部导航栏方法-----
			//退出系统
			loginout() {
				// #ifdef APP-PLUS
				plus.runtime.quit();
				// #endif
			},
			//返回上一步
			back() {
				// if(this.cameraId && this.openSourceMark) {
				// 	this.closePower(this.cameraId, this.openSourceMark)
				// }
				uni.navigateBack({
					delta: 1
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.contain-view {
		padding: 20rpx 20rpx 0;
	}
	.header {
		display: flex;
		margin-bottom: 20rpx;
		
		.title {
			width: calc(100% - 240rpx);
			font-size: 32rpx;
			padding: 6rpx 0 0 10rpx;
			color: #a18859;
			
			.icon {
				width: 30rpx;
				height: 30rpx;
				margin-right: 6rpx;
				vertical-align: middle;
			}
		}
		.toVideo {
			width: 230rpx;
			padding: 6rpx 10rpx;
			font-size: 28rpx;
			color: #fff;
			border-radius: 30rpx;
			background-image: linear-gradient(to right, #2767fe, #82a8ff);
			
			.icon {
				vertical-align: middle;
			}
		}
	}
	.select-camera {
		width: 100%;
		height: 50rpx;
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;

		// justify-content: space-between;
		.icon-sty {
			height: 40rpx;
			width: 60rpx;
			// margin-top: 10rpx;
		}

		.select-picker {
			// width: 200rpx;
			height: 50rpx;
		}
	}

	.text {}

	::v-deep {
		.uni-popup__wrapper {
			background-color: initial !important;
			color: #f0f0f0;
			font-size: 40rpx;
		}
	}

	.video-view {
		width: 686rpx;
		height: 410rpx;
		padding: 10rpx;
		background-color: #484848;

		.zhvideo-sty {
			width: 686rpx;
			height: 360rpx;

			.video-definition-btn {
				position: absolute;
				z-index: 99;
				top: 10;
				width: 150rpx;
				height: 50rpx;
				text-align: center;
				border-radius: 50rpx;
				background-color: #ffffff;
				color: #3bca99;
				font-size: 600;
				margin-left: 50rpx;
				margin-top: 20rpx;
				line-height: 40rpx;
			}
		}

		.fullscreen {
			width: 665rpx;
			height: 50rpx;

			.icon-sty {
				float: right;
				width: 40rpx;
				height: 40rpx;
			}
		}
	}

	.cotrol-view {
		margin-top: 40rpx;
		width: 100%;
		height: 350rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;

		.control-view-line1 {
			height: 350rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-around;

			image {
				margin-top: 10rpx;
				margin-right: 10rpx;
				height: 20rpx;
			}

			.tobig {}
		}

		.control-view-line2 {
			width: 232rpx;
			height: 230rpx;
			margin-top: 16rpx;
			background-color: rgba(50, 204, 151, 1);
			box-shadow: 0px 0px 8px rgba(33, 222, 157, 1);
			border-radius: 40rpx;
			padding: 10rpx;
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			transform: rotate(45deg);
			position: relative;

			.sanjiao:hover {
				animation: jelly 0.5s;
			}

			@keyframes jelly {

				0%,
				100% {
					transform: scale(1, 1);
				}

				25%,
				75% {
					transform: scale(0.9, 1.1);
				}

				50% {
					transform: scale(1.1, 0.9);
				}
			}

			.totop {
				width: 112rpx;
				height: 112rpx;
				border: 2rpx solid #efefef;
				display: flex;
				justify-content: center;
				align-items: center;
				border-top-left-radius: 40rpx;
				background-color: #ffffff;

				.sanjiao {
					width: 0;
					height: 0;
					border: 0;
					border: 20rpx solid transparent;
					border-top: 20rpx solid #32cc97;
					border-left: 20rpx solid #32cc97;
					// border-top: 50rpx #FFFDEF solid;
					// border-left: 50rpx #FFFDEF solid;
				}
			}

			.toright {
				width: 112rpx;
				height: 112rpx;
				border: 2rpx solid #efefef;
				background-color: #ffffff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-top-right-radius: 40rpx;

				.sanjiao {
					width: 0;
					height: 0;
					border: 0;
					border: 20rpx solid transparent;
					border-top: 20rpx solid #32cc97;
					border-right: 20rpx solid #32cc97;
				}
			}

			.tobottom {
				width: 112rpx;
				height: 112rpx;
				border: 2rpx solid #efefef;
				display: flex;
				background-color: #ffffff;
				justify-content: center;
				align-items: center;
				border-bottom-left-radius: 40rpx;

				.sanjiao {
					width: 0;
					height: 0;
					border: 0;
					border: 20rpx solid transparent;
					border-bottom: 20rpx solid #32cc97;
					border-left: 20rpx solid #32cc97;
				}
			}

			.toleft {
				width: 112rpx;
				height: 112rpx;
				border: 2rpx solid #efefef;
				background-color: #ffffff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-bottom-right-radius: 40rpx;

				.sanjiao {
					width: 0;
					height: 0;
					border: 0;
					border: 20rpx solid transparent;
					border-bottom: 20rpx solid #32cc97;
					border-right: 20rpx solid #32cc97;
				}
			}

			.fanzhuan {
				width: 50rpx;
				height: 50rpx;
				position: absolute;
				top: 100rpx;
				left: 100rpx;
				background-color: rgba(255, 255, 255, 1);
				border: 2rpx solid rgba(175, 235, 214, 1);
				box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.16);
				border-radius: 50%;
				background-image: url('@/static/instrumented-monitoring/video-surveillance/fanzhuan.png');
				background-repeat: no-repeat;
				background-position: center;
			}
		}

		.control-view-line3 {
			background-color: rgba(50, 204, 151, 1);
			box-shadow: 0px 0px 7px rgba(33, 222, 157, 1);
			border-radius: 20rpx;
			color: #ffffff;

			.icon-sty {
				height: 20rpx;
				margin-right: 10rpx;
			}
		}
	}

	.blank-view {
		width: 100%;
		height: 500rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.blank-sty {
			width: 400rpx;
			height: 400rpx;
		}

		.blank-title {
			width: 100%;
			height: 50rpx;
			color: #a1a1a1;
			line-height: 50rpx;
			text-align: center;
		}
	}

	::v-deep {
		.text {
			>span {
				display: inline-block;
				width: 100%;
				height: 100%;
			}
		}

		.uni-popup {
			>uni-view {
				>uni-view {
					margin-top: 140rpx;
					height: calc(100% - 240rpx);
					margin-bottom: 100rpx;
				}
			}
		}
	}
</style>
